package com.sgb.kjwl.viewmodel.shopping;

import android.content.Intent;

import com.alibaba.android.arouter.launcher.ARouter;
import com.chuanglan.shanyan_sdk.OneKeyLoginManager;
import com.sgb.goods.utils.Constants;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.api.service.WebsiteInfoAPI;
import com.sgb.kjwl.model.entity.CreateOrderEntity;
import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.request.CheckGoodsOrderEntity;
import com.sgb.kjwl.model.entity.request.CheckGoodsOrderResultEntity;
import com.sgb.kjwl.model.entity.request.SubmitGoodsOrderEntity;
import com.sgb.kjwl.model.entity.shopping.PurchasingTypeEntity;
import com.sgb.kjwl.model.entity.user.OneKeyLoginEntity;
import com.sgb.link.entity.InvoiceManagementEntity;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.self.OrderEvent;
import com.sgb.kjwl.view.ui.activity.ShoppingCar.StatementActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.SetPwdActivity;
import com.sgb.link.entity.WebSiteAddressEntity;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.base.model.entity.ListResponse;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import cn.jpush.android.api.JPushInterface;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author Administrator
 */
public class StatementModel {

    private final StatementActivity activity;

    public StatementModel(StatementActivity activity) {
        this.activity = activity;
    }

    /**
     * 地址列表查询
     * siteType 网站类型  0-个人 1-企业 2-团队
     */
    public void getDefaultAddress(int page, String limit, int siteType) {
        DialogHelper.showProgressDialog2(activity, null, "数据获取中...", 0, false, null, false);
        APIManager.getInstance().getWebsiteInfoAPI().getNewUserAddress(WebsiteInfoAPI.UserCenterUrl.URL_ADDRESS_LIST, limit, page, siteType).enqueue(new ICallBack<BaseEntity<ListResponse<List<WebSiteAddressEntity>>>>() {
            @Override
            public void onSuccess(BaseEntity<ListResponse<List<WebSiteAddressEntity>>> data) {
                if (data != null && data.getData() != null && data.getData().getList() != null && data.getData().getList().size() != 0) {
                    activity.initDefaultAddress(data.getData().getList());
                } else {
                    activity.showNoAddress();
                }
            }
        });

    }

    /***
     * 获取开票信息
     */
    public void getInvoiceInfo() {
        DialogHelper.showProgressDialog2(activity, null, "数据获取中...", 0, false, null, false);

        NewAPIManager.getInstance().getShoppingCarNewOrderAPI().getInvoiceInfoByUser().enqueue(new Callback<BaseEntity<List<InvoiceManagementEntity>>>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity<List<InvoiceManagementEntity>>> call, @NotNull Response<BaseEntity<List<InvoiceManagementEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    if (response.body().getData() != null && response.body().getData().size() != 0) {
                        activity.initDefaultInvoice(response.body().getData());
                    } else {
                        activity.invoiceEmpty();
                    }
                } else {
                    MToast.showToast(activity, response.message());
                }
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity<List<InvoiceManagementEntity>>> call, @NotNull Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(activity, t.getMessage());
            }
        });
    }

    /***
     * 获取订单采购/收货/装车/卸车/物流选择
     */
    public void getPurchasingMethod() {
        DialogHelper.showProgressDialog2(activity, null, "数据获取中...", 0, false, null, false);
        NewAPIManager.getInstance().getShoppingCarNewOrderAPI().getPurchasingMethod().enqueue(new Callback<BaseEntity<PurchasingTypeEntity>>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity<PurchasingTypeEntity>> call, @NotNull Response<BaseEntity<PurchasingTypeEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    if (response.body().getData() != null) {
                        activity.initPurchasingMethod(response.body().getData());
                    } else {
                        activity.invoiceEmpty();
                    }
                } else {
                    MToast.showToast(activity, response.message());
                }
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity<PurchasingTypeEntity>> call, @NotNull Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(activity, t.getMessage());
            }
        });
    }

    /**
     * 创建订单
     */
    public void createOrder(CreateOrderEntity createOrderEntity) {
        DialogHelper.showProgressDialog2(activity, null, "数据获取中...", 0, false, null, false);
        APIManager.getInstance().getOrderAPI().createOrder(createOrderEntity).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity> call, @NotNull Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    //跳转订单页面
                    MToast.showToast(activity, "提交成功");
                    EventBus.getDefault().postSticky(OrderEvent.make().setMessageTag(EventConstant.EVENT_ORDER_LIST_WAIT));
                    ARouter.getInstance().build(Constants.ARouter.AR_PURCHASE_ORDER_LIST).navigation();
                    activity.finish();
                } else {
                    MToast.showToast(activity, response.message());
                }
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity> call, @NotNull Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(activity, t.getMessage());
            }
        });
    }

    /***
     * 提交订单校验
     */
    public void checkCartItemPrice(List<CheckGoodsOrderEntity> cartItemPriceEntities) {
        DialogHelper.showProgressDialog2(activity, null, "获取信息中...", 0, false, null, false);
        NewAPIManager.getInstance().getShoppingCarNewOrderAPI().getCheckCartItemOrder(cartItemPriceEntities).enqueue(new Callback<BaseEntity<List<CheckGoodsOrderResultEntity>>>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity<List<CheckGoodsOrderResultEntity>>> call, @NotNull Response<BaseEntity<List<CheckGoodsOrderResultEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    if ("200".equals(response.body().getCode())) {
                        activity.setCheckResult(true, response.body().getData());
                    } else if ("500".equals(response.body().getCode())) {
                        activity.setCheckResult(false, response.body().getData());
                    }
                } else {
                    MToast.showToast(activity, response.body().getMsg());
                }

            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity<List<CheckGoodsOrderResultEntity>>> call, @NotNull Throwable throwable) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(activity, throwable.getMessage());
            }
        });
    }

    /***
     * 提交订单
     * @param
     */
    public void saveOrder(SubmitGoodsOrderEntity submitGoodsOrderEntity) {
        DialogHelper.showProgressDialog2(activity, null, "获取信息中...", 0, false, null, false);
        NewAPIManager.getInstance().getShoppingCarNewOrderAPI().saveOrder(submitGoodsOrderEntity).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity> call, @NotNull Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    MToast.showToast(activity, response.message());
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.setSubmitGoodsOrderSuccess(response.body().getMsg());
                }
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity> call, @NotNull Throwable throwable) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(activity, throwable.getMessage());
            }
        });
    }

    public void oneKeyLogin(OneKeyLoginEntity oneKeyLoginEntity) {
        if (activity != null && !activity.isFinishing() && !activity.isDestroyed()) {
            DialogHelper.showProgressDialog2(activity, null, "数据加载中...", 0, false, null, false);
        }
        APIManager.getInstance().getUserAPI().oneClickLogin(oneKeyLoginEntity).enqueue(new Callback<BaseEntity<LoginEntity>>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity<LoginEntity>> call, @NotNull Response<BaseEntity<LoginEntity>> response) {

                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    OneKeyLoginManager.getInstance().finishAuthActivity();
                    if (response.body().getData().isNeedRegister()) {
                        Intent intent = new Intent(activity, SetPwdActivity.class);
                        intent.putExtra("mobile", response.body().getData().getPhone());
                        activity.startActivity(intent);
                    } else {
                        //登录成功逻辑
                        loginImModel(response);
                    }
                }
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity<LoginEntity>> call, @NotNull Throwable throwable) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(activity, throwable.getMessage());
            }
        });
    }

    /**
     * 网易IM登陆
     */
    private void loginImModel(Response<BaseEntity<LoginEntity>> response) {
//        NimUIKit.login(new LoginInfo(response.body().getData().getImAccount(), response.body().getData().getImToken()), new RequestCallback<LoginInfo>() {
//            @Override
//            public void onSuccess(LoginInfo param) {
        DialogHelper.dismissProgressDialog();
        SharedPreferenceUtil.getInstance().cleatData();
        saveUserInfo(response.body().getData());
        MToast.showToast(activity, "登录成功");
        activity.loginSucceed(response.body().getData(), response.body().getData().getPhone());
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, response.body().getData().getToken());
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PHONE, response.body().getData().getPhone());
        JPushInterface.setAlias(activity, 1, response.body().getData().getPhone());
        getUserInfo();
//            }
//
//            @Override
//            public void onFailed(int code) {
//                DialogHelper.dismissProgressDialog();
//            }
//
//            @Override
//            public void onException(Throwable exception) {
//                DialogHelper.dismissProgressDialog();
//            }
//        });
    }

    private void saveUserInfo(LoginEntity loginEntity) {
//        NimUIKit.setAccount(loginEntity.getImAccount());
//        AVChatKit.setAccount(loginEntity.getImAccount());
        //Preferences.saveUserAccount(loginEntity.getImAccount());
        //       Preferences.saveUserToken(loginEntity.getImToken());
    }

    public void getUserInfo() {
        if (activity != null && !activity.isFinishing() && !activity.isDestroyed()) {
            DialogHelper.showProgressDialog2(activity, null, "数据加载中...", 0, false, null, false);
        }
        APIManager.getInstance().getUserAPI().getUserInfo().enqueue(new Callback<BaseEntity<UserMsgEntity>>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity<UserMsgEntity>> call, Response<BaseEntity<UserMsgEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getData() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.getUserMsgSucceed(response.body().getData());
                } else {
                    MToast.showToast(activity, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity<UserMsgEntity>> call, @NotNull Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public List<String> setTag() {
        List<String> tags = new ArrayList<>();
        tags.add("默认");
        return tags;
    }

}
